<?php
    //v 6
    //5 - get_end set_end; 
    //6 - get_array set_array

    class t
    {
        static $progress = array();
        static $param = array();
        static $info = array();
        //текущая задача с котрой работаем
        static $name = null;
        static $class = null;
        //proc
        static $cur = null;
        static $end = null;
        static $status = null;
        static $time = null;
        static $in = array();

        public static function install()
        {
        }

        //существует ли задача
        public static function is_task($name, $group = 'main')
        {
            $file = DATA_PATH . 'task.'.$group.':'.$name.'.dat';
            if ( is_file( $file ) )
            {
                if ( filesize ( $file ) > 0 )
                {
                    return true;
                }
                else
                {
                    return false;
                    log::add('is_task', 'empty. '.'task.'.$group.':'.$name.'.dat');
                    //  @unlink( $file );
                }
            }
            else
            {
                return false;
            }       
        }

        public static function get_array($name, $group = 'main')
        {
            if ( is_null(self::$name) )
            {
                return false;
            }
            else
            {
                $in =  m::json_data_read('task.'.$group.':'.self::$name.'.dat');
                return $in[$name];
            }

        }   

        public static function set_array($name, $value, $group = 'main')
        {
            if ( !is_null(self::$name) and self::is_task(self::$name, $group) )
            {
                $in = m::json_data_read('task.'.$group.':'.self::$name.'.dat');

                if ( is_array($in) and count($in) >0)
                {
                    $in[$name] =  $value;
                    m::json_data_save('task.'.$group.':'.self::$name.'.dat', $in);  
                    return true; 
                }
            }
            else
            {
                return false;
            } 
        }

        public static function task_array ()
        {
            $array = m::file_list(DATA_PATH);

            $op = array();
            if ( is_array($array) and count($array) > 0)
            {

                foreach ($array as $val)
                {
                    $opt = explode('.', $val);

                    if (count($opt)== 3)  
                    {

                        $format = trim( strtolower(  $opt[count($opt)-1] ) );

                        if ($format == 'dat')
                        {
                            unset($opt[count($opt)-1]);


                            $name = $opt[0];
                            unset($opt[0]);

                            if ($name == 'task')
                            {
                                $val = $opt[1];
                                $opt2 = explode(':', $val);
                                if ( is_array($opt2) and  count($opt2)  == 2)
                                {
                                    if ( !in_array($opt2[1], $op) )
                                    {

                                        $op[ $opt2[1]] = $opt2[0]; 
                                    }

                                }
                            }
                        }
                    }   
                }
            }

            return $op;
        }

        public static function get()
        {
            $m = t::task_array();

            $info = array();
            if ( is_array($m) and count($m) > 0)
            {
                foreach ($m as $n => $v)
                {
                    $in = m::json_data_read('task.'.$v.':'.$n.'.dat');

                    if ( !empty($in))
                    {
                        $info[ $n ]  = $in;
                    }
                }
            }


            /* if ( !is_null(self::$name) )
            {
            self::$in = self::$info[self::$name];

            self::$time = self::$in['time']; 
            self::$cur = self::$in['proc']['cur']; 
            self::$end = self::$in['proc']['end']; 
            }   
            else
            {
            self::$in = array();

            self::$time = ''; 
            self::$cur = ''; 
            self::$end = ''; 
            }
            */

            return $info; 
        }

        public static function set_alt($value, $group = 'main')
        {
            if ( !is_null(self::$name) and self::is_task(self::$name, $group) )
            {
                $in = m::json_data_read('task.'.$group.':'.self::$name.'.dat');

                if ( is_array($in) and count($in) >0)
                {
                    $in['pro_alt'] =  $value;
                    m::json_data_save('task.'.$group.':'.self::$name.'.dat', $in);  
                    return true; 
                }
            }
            else
            {
                return false;
            } 
        }

        public static function set_cur($value, $group = 'main')
        {
            if ( !is_null(self::$name) and self::is_task(self::$name, $group) )
            {
                $in = m::json_data_read('task.'.$group.':'.self::$name.'.dat');

                if ( is_array($in) and count($in) >0)
                {
                    $in['proc']['cur'] =  $value;
                    m::json_data_save('task.'.$group.':'.self::$name.'.dat', $in);  
                    return true; 
                }
            }
            else
            {
                return false;
            } 
        }

        public static function get_cur($name ='', $group = 'main')
        {
            if ( is_null(self::$name) )
            {
                return false;
            }
            else
            {
                $in =  m::json_data_read('task.'.$group.':'.self::$name.'.dat');
                return $in['proc']['cur'];
            }

        }          

        public static function get_end($name ='', $group = 'main')
        {
            if ( is_null(self::$name) )
            {
                return false;
            }
            else
            {
                $in =  m::json_data_read('task.'.$group.':'.self::$name.'.dat');
                return $in['proc']['end'];
            }

        }   

        public static function set_end($value, $group = 'main')
        {
            if ( !is_null(self::$name) and self::is_task(self::$name, $group) )
            {
                $in = m::json_data_read('task.'.$group.':'.self::$name.'.dat');

                if ( is_array($in) and count($in) >0)
                {
                    $in['proc']['end'] =  $value;
                    m::json_data_save('task.'.$group.':'.self::$name.'.dat', $in);  
                    return true; 
                }
            }
            else
            {
                return false;
            } 
        }

        public static function set_status($name, $value, $group = 'main')
        {
            return self::status($name, $value, $group);
        }

        public static function status($name, $value, $group = 'main')
        {
            if ( self::is_task($name, $group) )
            {
                $in = m::json_data_read('task.'.$group.':'.$name.'.dat');

                if ( is_array($in) and count($in) >0 and isset($in['status']) )
                {
                    self::$status = (int)$value;
                    $in['status'] = (int)$value;
                    m::json_data_save('task.'.$group.':'.$name.'.dat', $in);  
                    return true; 
                }
            }
            else
            {
                return false;
            } 
        }

        //добавление задачи
        public static function add($name, $option= array(), $group = 'main')
        { 
            if ( !is_null(self::$class) )
            {
                $option['class'] = self::$class; 
            }

            $option['group'] = $group;
            $option['time'] = 0;

            if ( !isset($option['status']))
            {
                $option['status'] = 0;
            }

            if ( !isset($option['last_time']))
            {
                $option['time'] =  0;
            }


            if ( !isset($option['pro']))
            {
                $option['proc'] = array('cur' => 0, 'end' => 0); 
            }

            m::json_data_save('task.'.$group.':'.$name.'.dat', $option); 

            return true;
        }

        // if ( !is_null(self::$end) and isset(self::$info[self::$name]['proc']['end']) )   self::$info[self::$name]['proc']['end'] = self::$end;  
        //if ( !is_null(self::$cur) and isset(self::$info[self::$name]['proc']['cur']) )   self::$info[self::$name]['proc']['cur'] = self::$cur; 


        public static function remove($name, $group = 'main')
        {

            if ( self::is_task($name, $group) )
            {
                unlink (DATA_PATH . 'task.'.$group.':'.$name.'.dat');
                log::add('task remove', 'task remove. task.'.$group.':'.$name.'.dat');
                return true;  
            } 
            else
            {
                return false;
            }
        }

        public static function remove_class($class = '')
        {
            $m = self::task_array();

            if ( !empty($class))
            {
                if ( is_array($m) and count($m) > 0)
                {
                    foreach ($m as $n => $v)
                    {
                        $in = m::json_data_read('task.'.$v.':'.$n.'.dat');

                        if ( !empty($in) and isset($in['class']) and $in['class'] == $class)
                        {
                            @ unlink(DATA_PATH . 'task.'.$v.':'.$n.'.dat');
                        }
                    }
                }
            }
            else
            {
                return false;
            }
        }

        public static function run()
        {
            $info = self::get(); 
            self::$info = $info;
            $run = array();
            $time_zero = array();
            $interval = array();
            $runner = array();

            if ( count( $info ) > 0 )
            {
                foreach ($info as $name => $val)
                {
                    if (isset($val['status']) and $val['status'] ==1)
                    {                     
                        if ($val['time'] == 0) 
                        {
                            $time_zero[] = $name;    
                            $runner[ $name ] = 0;
                        }
                        else
                        {
                            if (!isset($val['interval']))
                            {
                                $run[ $val['time'] ] = $name;  
                                $runner[ $name ] = $val['time'] ;   
                            }      
                        }         
                    }

                    if ( isset($val['interval']) and !empty($val['interval']) )
                    {
                        if ( time() - $val['time'] > $val['interval'])
                        {
                            $interval[ time() - $val['time'] ] = $name;    
                            $runner[ $name ] = $val['time'];  
                        }
                    }

                    if ($val['status']==2)
                    {
                        if ( time()-$val['time'] > 180 )
                        {
                            self::status($name, 1);
                            $run[ $val['time'] ] = $name;       
                        } 
                    } 
                }
            }

            if ( count($runner) > 0)
            {
                if ( count($runner) > 1)
                {
                    asort($runner);
                }

                $run_name = each($runner); 
                $run_name = $run_name['key']; 

                self::do_action($run_name);  
            }
            else
            {
                echo 'no';
            }
        }

        public static function set_time ()
        {
            if ( is_null(self::$name) )
            {
                return false;
            }
            else
            {
                $name = self::$name;
                $group = 'main';

                $in = m::json_data_read( 'task.'.$group.':'.$name.'.dat' );

                if ( is_array($in) and count($in) > 0)
                {
                    $in['time'] = time();
                    m::json_data_save('task.'.$group.':'.$name.'.dat', $in); 
                }
            }
        }    


        public static function get_status($name, $group = 'main')
        {
            if ( self::is_task($name, $group))
            {
                $in =  m::json_data_read('task.'.$group.':'.$name.'.dat');
                if ( isset($in['status']))
                {
                    return $in['status'];
                }
            }
            else
            {
                return false;
            }
        }    

        public static function get_name($name, $group = 'main' )
        {
            if ( self::is_task($name, $group))
            {
                $in =  m::json_data_read('task.'.$group.':'.$name.'.dat');
                return $in;
            }
            else
            {

                return false;
            }
        }

        public static function do_action($run_name, $group = 'main')
        {
            $info = t::get_name($run_name);

            if ( empty($info))
            {
                echo 'no';
                return;
            }

            $action = $info['func'];


            $r = explode('::', $action);

            if ( method_exists( $r[0], $r[1] ) ) 
            {
                echo '<i>'.date("H:i:s").' <b>'. $run_name.'</b>;';
                self::$name = $run_name;
                self::set_time();
                self::status($run_name, 2);

                $t1 = microtime(true);

                ob_start();  
                self::$class = $r[0];
                call_user_func( array( $r[0], $r[1] ) );
                self::$class = null; 
                $t = ob_get_contents();
                ob_end_clean();


                $t2 = microtime(true);

                echo ' t: '. round($t2-$t1,2).'; </i> '; 
                echo '<b>'.$t.'</b> ';

                if ( t::get_status($run_name) == 2)
                {
                    t::status($run_name, 1);
                }

                self::$name = null;  
            }
            else
            {
                echo 'method error';
            }
        }

        public static function get_list()
        {
            $array = t::get();   

            ob_start();  
            if ( count($array) == 0 )
            {
                echo 'ok';
            }
            else
            {
                echo '<table border="0" width="100%" class="tsk">';
                echo '<tr align="center" class="head">
                <td>plug</td>
                <td>title</td>
                <td>time</td>
                <td>int</td>
                <td>func name</td>  
                <td>status</td>  
                <td>progress</td>  
                <td>progress desc</td>  
                <td colspan="5">action</td>   
                </tr>';
                foreach ($array as $name => $val)
                {
                    if ( $val['status'] > 0)
                    {
                        echo '<tr align="center" bgcolor="#dbffdb">';
                    }
                    else
                    {
                        echo '<tr align="center" bgcolor="#ffe9e9">';     
                    }
                    echo '<td align="left">&nbsp;&nbsp;'.$val['class'].'</td>'; 
                    echo '<td align="left">&nbsp;&nbsp;'.$val['alt'].'</td>'; 

                    if ( !empty( $val['time'] ))
                    {
                        $time  =   gmdate("d.m.y h:i:s", $val['time']);

                    }
                    else
                    {
                        $time = 'нет';
                    }


                    echo '<td align="center">'.$time.'</td>'; 

                    if ( isset($val['interval']))
                    {
                        echo '<td align="center">'.round($val['interval']/60, 0).'m</td>'; 
                    }
                    else
                    {
                        echo '<td align="center">нет</td>';    
                    }

                    $func = explode('::', $val['func']);
                    $func = $func[1];
                    echo '<td><b>'.$func.'</b></td>';
                    if ( isset($val['status']) ) 
                    {
                        echo '<td width="40px" align="center">'.@$val['status'].'</td>';
                    }
                    else
                    {
                        echo '<td width="40px" align="center"></td>';    
                    }

                    if ( isset( $val['proc']))
                    {
                        echo '<td align="center">'.''.$val['proc']['cur'].' ~ '.$val['proc']['end'].'</td>';  
                    }
                    else
                    {
                        echo '<td align="center">&nbsp;</td>';
                    }

                    if ( isset($val['pro_alt']) and !empty($val['pro_alt']) )
                    {
                        if ( isset($val['func_pro']) and !empty($val['func_pro']))
                        {
                            echo '<td width="100px"><a class="fancybox fancybox.ajax" href="admin.php?page=task.pro&task_name='.$name.'">'.$val['pro_alt'].'</a></td>';
                        }
                        else
                        {
                            echo '<td width="100px">'.$val['pro_alt'].'</td>';

                        }
                    }
                    else
                    {
                        echo '<td width="100px"></td>';
                    }                   

                    if ( isset($val['status'])  and ( $val['status'] == 1 or $val['status'] == 2))  
                    {
                        echo '<td width="40px"><a href="#" class="stop_action" id="'.$name.'">stop</a></td>';
                    }
                    else
                    {
                        echo '<td width="40px"></td>';
                    }

                    echo '<td width="40px"><a href="#" class="run_action" id="'.$name.'">run</a></td>';


                    if ( isset($val['status'])  and ($val['status'] == 2 or $val['status']==0) )  
                    {
                        echo '<td width="40px"><a href="#" class="start_action" id="'.$name.'">start</a></td>';
                    }
                    else
                    {
                        echo '<td width="40px"></td>';
                    }  

                    if ( isset($val['status'])  and ($val['status'] == 2 or $val['status']==0 or $val['status'] == 1) )  
                    {
                        echo '<td width="40px"><a href="#" class="restart_action" id="'.$name.'">restart</a></td>';
                    }
                    else
                    {
                        echo '<td width="40px"></td>';
                    }


                    echo '<td width="40px"><a href="#" class="remove_action" id="'.$name.'">del</a></td>';

                    echo '</tr>';
                }
                echo '</table>';
            }

            $t = ob_get_contents();
            ob_end_clean();
            return $t;        

        }

    }
?>
